package com.blood.config.handler;

import com.blood.core.resp.BusinessException;
import com.blood.core.resp.GlobalResultStatus;
import com.blood.core.resp.ResponseResult;
import com.blood.modules.system.dto.req.SysLogSaveReq;
import com.blood.modules.system.service.ISysLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * @author yelong
 * @version 1.0
 * @date 2020/9/12 10:35
 * @description 通用异常处理器
 */
@RestControllerAdvice
@Configuration
@Slf4j
public class CommonExceptionHandler {
    @Value("${logging.exceptionInfo}")
    private String exceptionInfo;

    @Autowired
    private ISysLogService sysLogService;

    public CommonExceptionHandler() {
        log.info("-----> 通用异常处理器自动配置完成");
    }

    @ExceptionHandler(value = Throwable.class)
    public ResponseResult<Void> dealException(Throwable e) {
        log.error("错误原因：{}", e.getMessage());
        if (Boolean.valueOf(exceptionInfo)) {
            log.error("错误详情：", e);
        }

        if (e instanceof BusinessException) {
            BusinessException be = (BusinessException) e;
            return new ResponseResult<>(false, be.getErrorCode(), be.getErrorMsg(), null);
        }
        //保存错误日志
        SysLogSaveReq req = new SysLogSaveReq();
        req.setInfo(e.getMessage());
        sysLogService.saveInfo(req);

        if (e instanceof Exception) {
            return GlobalResultStatus.FAIL.toResult("系统错误,请稍后重试!").responseEmptyBody();
        }
        return GlobalResultStatus.SYS_ERROR.toResult().responseEmptyBody();
    }

}
